<?php

namespace App\Console\Commands\Tools\Douyin;

use App\Kuafu\Pay\BasePay;
use App\Kuafu\Pay\Channel\FuYou\FuYouBase;
use App\Kuafu\Pay\Service\PayService;
use App\Kuafu\Shop\Enum\ShopCacheEnum;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\ShopCameraSyncService;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Library\FeiShu\SendFs;
use App\Remote\Tiger\Common\CommonRemote;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class DouyinRefreshProductCommand extends Command
{
    protected $signature = 'tools:douyin:refresh-product';

    protected $description = '抖音刷新商品适用门店';

    private string $cache_suffix = '1706';

    public function handle()
    {
        // 校验 cookie
        $dyList = $this->getProductList(10);

        if ($dyList['status_code']) {
            SendFs::newRobot()
                  ->forceSetRobot('https://open.feishu.cn/open-apis/bot/v2/hook/df38d121-63f4-407d-ad14-cd5dca6d02bc',
                      '65KyhxrfPY2Ih2FtBt1H7g')
                  ->setTitleContent('抖音来客Cookie 过期了,快更新!', date('Y-m-d') . '记得更新~')
                  ->setAtUid('f86ddcgf')
                  ->setAtUid('3fgc8798')
                  ->send();
            return;
        }

        $productList = Cache::remember('DouyinRefreshProductCommand' . $this->cache_suffix, 1800, function () {
            $productList = $this->getAllProductList();
            return $productList;
        });

        $this->info('商品数据抓取成功, 共计' . count($productList) . '件商品');
        $this->info('---------------------');

        foreach ($productList as $item) {
            $list = $this->getAllShopList($item['product_id']);

            $this->info("{$item['product_name']}商品适用门店抓取成功, 共计" . count($list) . "家门店");

            $poiList = array_column($list, 'poi_id');

            $redisKey = ShopCacheEnum::getDouyinProductShopListBySkuId($item['product_id']);

            Redis::set($redisKey, json_encode($poiList), 'EX', 87400 * 24 * 30); // 管 30 天
        }

    }


    public function getAllProductList()
    {
        $dyList = Cache::remember('DouyinRefreshProductCommand3_getAllProductList_1', 1800, function () {
            $dyList = $this->loopProductList();
            return $dyList;
        });

        $formatList = [];
        foreach ($dyList as $item) {

            $productInfo = $item['product'];

            if ($productInfo['product_type'] == 11) {
                continue;
            }

            $formatList[$productInfo['product_id']] = [
                'product_type' => $productInfo['product_type'],
                'product_id'   => $productInfo['product_id'],
                'product_name' => $productInfo['product_name'],
            ];
        }

        return $formatList;
    }

    public function loopProductList(int $cursor = 0, string $searchAfter = '')
    {
        $list   = [];
        $num    = 50;
        $dyList = $this->getProductList($num, $cursor, $searchAfter);

        $cursor      = $dyList['cursor'] ?? -1;
        $searchAfter = $dyList['search_after'] ?? '';

        if ($cursor > 0) {
            // 还有多的
            $list   = array_merge($list, $dyList['product_detail_list']);
            $dyList = $this->loopProductList($cursor, $searchAfter);
            $list   = array_merge($list, $dyList);
            return $list;
        } else {
            // 循环结束
            return $list;
        }
    }

    public function getProductList(int $num = 50, int $cursor = 0, string $searchAfter = '')
    {

        $client  = new Client();
        $headers = [
            'authority'           => 'life.douyin.com',
            'ac-tag'              => 'ka_10h',
            'accept'              => 'application/json, text/plain, */*',
            'accept-language'     => 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
            'agw-js-conv'         => 'str',
            'content-type'        => 'application/json',
            'cookie'              => $this->getCookie(),
            'dnt'                 => '1',
            'origin'              => 'https://life.douyin.com',
            'referer'             => 'https://life.douyin.com/p/goods?activeTabKey=9&groupid=1732447317648398',
            'sec-ch-ua'           => '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
            'sec-ch-ua-mobile'    => '?0',
            'sec-ch-ua-platform'  => '"macOS"',
            'sec-fetch-dest'      => 'empty',
            'sec-fetch-mode'      => 'cors',
            'sec-fetch-site'      => 'same-origin',
            'user-agent'          => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
            'x-secsdk-csrf-token' => '000100000001752dc3e02cbaa3a5f7bb6b23206bccfe7f08e00b054eede51114237a40672db5177e3dd6db8dbd25',
            'x-tt-ls-session-id'  => 'bd9f08c8-d0ed-41f7-8fb7-ebbe6f8f93a7',
            'x-tt-trace-id'       => '00-26b86bbc1813fa6fb413491cb-26b86bbc1813fa6f-01',
            'x-tt-trace-log'      => '01'
        ];
        $body    = '{
  "exclude_poi_info": true,
  "product_type_list": [
    "1",
    "11",
    "12",
    "15"
  ],
  "filter_status": 9,
  "cursor": "' . $cursor . '",
  "count": ' . $num . ',
  "search_after": "' . $searchAfter . '",
  "search_param_str": "{\"SearchAllAccountPoiType\":0,\"ExpandToPoiAccount\":true,\"SearchAllAccountPoiStatus\":0,\"RelationTypes\":[1],\"SettleStatusBeforeClaim\":[],\"Selections\":[]}",
  "permission_common_param": {
    "all_selected_params": "{\"SearchAllAccountPoiType\":0,\"ExpandToPoiAccount\":true,\"SearchAllAccountPoiStatus\":0,\"RelationTypes\":[1],\"SettleStatusBeforeClaim\":[],\"Selections\":[]}"
  }
}';
        $request = new Request('POST',
            'https://life.douyin.com/life/goods/product/list/v2?ac_app=10148&root_life_account_id=7089001835192649766',
            $headers, $body);
        $res     = $client->sendAsync($request)->wait();
        $data    = $res->getBody();
        return json_decode($data, 1);
    }

    public function getAllShopList(string $pid): array
    {
        return Cache::remember('dy_getAllShopList' . $pid . '_' . $this->cache_suffix, 6000, function () use ($pid) {
            $list    = [];
            $pageNum = 1;
            do {
                sleep(random_int(1, 10));
                $shopList = $this->getShopList($pid, $pageNum);
                $poiList  = $shopList['poi_list'];
                $page     = $shopList['page'];
                $list     = array_merge($list, $poiList);
                $pageNum++;
            } while ($page['has_more']);

            return $list;
        });

    }

    public function getShopList(string $product_id, int $page = 1)
    {

        $client  = new Client();
        $headers = [
            'authority'           => 'life.douyin.com',
            'ac-tag'              => 'ka_10h',
            'accept'              => 'application/json, text/plain, */*',
            'accept-language'     => 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7,zh-TW;q=0.6',
            'agw-js-conv'         => 'str',
            'content-type'        => 'application/json',
            'cookie'              => $this->getCookie(),
            'dnt'                 => '1',
            'origin'              => 'https://life.douyin.com',
            'referer'             => 'https://life.douyin.com/p/goods_v2/detail?filter_status=9&groupid=1732447317648398&product_id=1767552406144023',
            'sec-ch-ua'           => '"Chromium";v="116", "Not)A;Brand";v="24", "Google Chrome";v="116"',
            'sec-ch-ua-mobile'    => '?0',
            'sec-ch-ua-platform'  => '"macOS"',
            'sec-fetch-dest'      => 'empty',
            'sec-fetch-mode'      => 'cors',
            'sec-fetch-site'      => 'same-origin',
            'user-agent'          => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
            'x-secsdk-csrf-token' => '00010000000107e9c27127c2acb36b1b8494f70e5c678a7bd72e8bc0be4e60b4a1cdad880f43177e4a45616ffaf7',
            'x-tt-ls-session-id'  => '7969e757-702c-4d40-a26b-f770d3c22446',
            'x-tt-trace-id'       => '00-27124ead181b8c55abec491cb-27124ead181b8c55-01',
            'x-tt-trace-log'      => '01'
        ];
        $body    = '{
  "product_id": "' . $product_id . '",
  "is_draft": false,
  "need_settle_account_name": true,
  "settle_type": 2,
  "page": ' . $page . ',
  "page_size": 100,
  "poi_set_id": "",
  "permission_common_param": {
    "all_selected_params": "{\"SearchAllAccountPoiType\":0,\"ExpandToPoiAccount\":true,\"SearchAllAccountPoiStatus\":0,\"RelationTypes\":[1],\"SettleStatusBeforeClaim\":[],\"Selections\":[]}"
  }
}';
        $request = new Request('POST',
            'https://life.douyin.com/life/goods/product/poi/bind/detail/page?root_life_account_id=7089001835192649766',
            $headers, $body);
        $res     = $client->sendAsync($request)->wait();
        $data    = $res->getBody();
        return json_decode($data, 1);
    }

    public function getCookie()
    {
        $cookie = CommonRemote::getConfigDetail('guanyuanDB', 'douyinLife[13522903770]')["value"];

        return $cookie;
    }
}
